#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-08-07 14:31
# @Author   : BYF
# file      : file_manager.py
# @version  :

import os
import csv
import codecs
import zipfile
from zipfile import ZipFile
from datetime import datetime
from lefull.common.excel import Excel


class FileManager():
    def __init__(self):

        pass

    @staticmethod
    def get_data_path(case_path):
        """
        根据测试文件获取测试数据地址
        :param case_path:测试文件路径
        :return:数据文件地址
        """
        file_path, file_name = os.path.split(case_path)
        temp_path = file_path.replace("case", "params")
        temp_name = file_name.replace(".py", ".xlsx")
        data_path = os.path.join(temp_path, temp_name)
        return data_path

    @classmethod
    def get_case_data(cls, path):
        """
        获取测试数据
        :param path:
        :return:
        """
        data_path = cls.get_data_path(path)  # 获取测试数据路径
        excel_data = Excel().read_excel(data_path)  # 获取测试数据
        interface_name, case_name, case_data = excel_data
        return interface_name, case_name, case_data

    @staticmethod
    def zip_file(dir_path, zip_file_name):
        """
        压缩指定文件夹
        :param dir_path:需要zip文件目录
        :param zip_file_name: zip后保存的路径+文件名
        :return:
        """
        zip = ZipFile(zip_file_name, mode="w", compression=zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dir_path):  # 遍历dir_path目标文件夹，拿到文件夹路径，及下层文件夹名称和文件名
            file_path = path.replace(dir_path, "")  # 将文件从目标文件夹进行切割，去掉目标文件根路径，只对目标文件下边的文件及文件夹进行压缩

            for filename in filenames:
                zip_file_path = os.path.join(path, filename)  # zip 文件路径
                zip_arcname = os.path.join(file_path, filename)  # zip 后文档保存的路径和名称
                zip.write(zip_file_path, zip_arcname)  # 将指定文件添加到zip文档中\
        zip.close()

    @staticmethod
    def backup_file(old_dir, new_dir):
        """
        备份老文件或目录
        :param old_dir:修改前目录
        :param new_dir:修改后目录
        :return:
        """
        try:
            os.rename(old_dir, new_dir)
            os.makedirs(old_dir)
        except Exception as e:
            print(e)
            print(f"请检查文件路径，当前路径为：{old_dir}")
        # 重新创建老的目录



    @staticmethod
    def get_csv(file_name):
        """
        获取CSV数据
        :return:
        """
        testdata = []

        with codecs.open(file_name, "rU", "UTF-8") as test_file:
            csv_file = csv.reader(test_file, dialect="excel")
            # CSV文件从第二行开始
            next(csv_file)
            for i in csv_file:
                # i = map(lambda arg : arg.decode('utf-8'), i)
                testdata.append(tuple(i))
        testdata = tuple(testdata)
        return testdata


if __name__ == '__main__':
    # project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # dir_path = os.path.join(project_dir, "case/learn_pytest")
    # zip_file_path = os.path.join(project_dir, "report/report.zip")
    # case_path = "/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/case/uponcommision/test_commision_role_list.py"
    # get_data_path(case_path)
    # print(os.path.abspath(__file__))
    case_path = "/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/report/xml/xml_report1"
    # 判断目录是否存在
    print(os.path.exists(case_path))
    # os.makedirs(case_path)

    now = datetime.now()
    print(now.strftime("%Y-%m-%d %H:%M:%S"))
    # 如果不存在则创建目录

    # 如果存在则备份目录，然后创建新目录
